package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Slf4j
@WebFilter(filterName ="loginFilter" ,urlPatterns = "/*")
public class LoginFilter implements Filter {

    private static AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain Chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取本次请求的URI
        String uri = request.getRequestURI();
        log.info("本次拦截到的请求:{}",uri);
        //2.判断本次请求是否需要处理
        String[] urls={
          "/employee/login",
          "/employee/logout",
          "/backend/**",
           "/front/**",
            "/common/**",
            "/user/**",
             "/wx/notify"//此地址 由微信服务器访问,必须放行
        };
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, uri);
            if (match){
                //放行请求
                //3.如果不需要处理,直接放行
                Chain.doFilter(request,response);
                return;
            }
        }
        //4.判断登录状态,自己已登陆,则直接放行
        //4.1获得用户登录信息
        HttpSession session = request.getSession();
        Long employee = (Long) session.getAttribute("employee");
        Long userId = (Long) session.getAttribute("userId");
        //判断条件改变
        if (employee == null && userId == null){
            //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
            String jsonString = JSON.toJSONString(R.error("NOTLOGIN"));
            response.getOutputStream().write(jsonString.getBytes());
            return;
        }
        if (employee!=null){
            BaseContext.threadLocal.set(employee);
        }else if (userId != null){
            BaseContext.threadLocal.set(userId);
        }
        //最终放行,原因 用户已登录
        //在线程绑定对象里存储一个userId
        Chain.doFilter(request,response);
        return;
    }
}
